<template>
  <view class="container">
    <view class="item" v-for="(item, index) in list" :key="item.id">
      <checkbox :checked="item.checked" @click="itemClick(index)"></checkbox>
      <view>{{ item.name }}</view>
      <view>￥{{ item.price }}</view>
      <view class="right">
        <button size="mini">-</button>
        <text>{{ item.count }}</text>
        <button size="mini">+</button>
      </view>
    </view>
    <view class="bottom">
      <checkbox :checked="isAll" @click="clickAll"></checkbox>
      <text>全选</text>
      <text class="total">总价:{{ totalPrice }}元</text>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from "vue";
const list = reactive([
  { id: 1001, name: "西游记", price: 10, count: 5, checked: true },
  { id: 1002, name: "红楼梦", price: 20, count: 2, checked: true },
  { id: 1003, name: "水浒传", price: 30, count: 2, checked: true },
  { id: 1004, name: "三国演义", price: 10, count: 2, checked: true },
]);

//计算总价
// const totalPrice = computed(() => {
//   return list.reduce((total, item, index, arr) => {
//     if (item.checked) {
//       return (total += item.price * item.count);
//     } else {
//       return total;
//     }
//   }, 0);
// });

const totalPrice = computed({
  get() {
    return list.reduce((total, item, index, arr) => {
      if (item.checked) {
        return (total += item.price * item.count);
      } else {
        return total;
      }
    }, 0);
  },
  set() {},
});

//点击单选
const itemClick = function (index: number) {
  list[index].checked = !list[index].checked;
};

//是否全选
const isAll = computed({
  get() {
    return list.every((item) => item.checked);
  },
  set(val) {
    list.forEach((item) => (item.checked = val));
  },
});

//点击全选
const clickAll = function () {
  isAll.value = !isAll.value;
};
</script>

<style style="less" scoped>
.item {
  display: flex;
}
.right {
  margin-left: 20rpx;
}
.total {
  margin-left: 30rpx;
}
</style>
